package com.agriculture.controller;

import com.agriculture.common.Response;
import com.agriculture.domain.Product;
import com.agriculture.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.ArrayList;
import java.util.UUID;

@RestController
@RequestMapping("/api/farmer/products")
@CrossOrigin
public class FarmerProductController {
    
    private static final Logger logger = LoggerFactory.getLogger(FarmerProductController.class);
    
    private static final String UPLOAD_PATH = "D:/agriculture/src/main/resources/static/uploads/images";
    private static final String URL_PREFIX = "/uploads/images/";
    
    @Autowired
    private ProductService productService;
    
    @PostMapping("/upload")
    public Response<?> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Response.error("上传文件不能为空");
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Response.error("只能上传图片文件");
            }
            
            // 使用原始文件名
            String fileName = file.getOriginalFilename();
            
            // 确保目录存在
            File uploadDir = new File(UPLOAD_PATH);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 保存文件
            File destFile = new File(UPLOAD_PATH + File.separator + fileName);
            file.transferTo(destFile);
            
            // 只返回文件名，不包含路径前缀
            logger.info("图片上传成功: {}", fileName);
            return Response.success("上传成功", fileName);
            
        } catch (IOException e) {
            logger.error("图片上传失败", e);
            return Response.error("图片上传失败: " + e.getMessage());
        }
    }

    @GetMapping
    public Response<?> getProducts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam Long ownerId,
            @RequestParam(required = false) String ownerType
    ) {
        try {
            logger.info("Controller接收参数: page={}, pageSize={}, keyword={}, category={}, ownerId={}, ownerType={}", 
                page, pageSize, keyword, category, ownerId, ownerType);
            
            int offset = (page - 1) * pageSize;
            List<Product> products = productService.getProductsByPage(
                ownerId, ownerType, keyword, category, offset, pageSize);
            int total = productService.getProductsCount(ownerId, ownerType, keyword, category);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", products);
            result.put("total", total);
            
            return Response.success("获取成功", result);
        } catch (Exception e) {
            logger.error("获取商品列表失败", e);
            return Response.error("获取商品列表失败: " + e.getMessage());
        }
    }

    @PostMapping
    public Response<?> addProduct(@RequestBody Map<String, Object> data) {
        try {
            // 打印完整的请求数据
            logger.info("接收到的完整请求数据: {}", data);
            
            // 验证必要字段
            List<String> missingFields = new ArrayList<>();
            String[] requiredFields = {
                "productName", "product_name",  // 至少需要其中一个
                "type",
                "category",
                "price",
                "unit",
                "stock",
                "ownerId", "owner_id",         // 至少需要其中一个
                "ownerType", "owner_type"      // 至少需要其中一个
            };
            
            // 检查必要字段
            for (int i = 0; i < requiredFields.length; i += 2) {
                String field1 = requiredFields[i];
                String field2 = i + 1 < requiredFields.length ? requiredFields[i + 1] : null;
                
                if (field2 != null) {
                    // 检查配对字段（允许任意一个存在）
                    if (data.get(field1) == null && data.get(field2) == null) {
                        missingFields.add(field1 + " 或 " + field2);
                    }
                } else {
                    // 检查单个必要字段
                    if (data.get(field1) == null) {
                        missingFields.add(field1);
                    }
                }
            }
            
            if (!missingFields.isEmpty()) {
                String errorMsg = "缺少必要字段: " + String.join(", ", missingFields);
                logger.error(errorMsg);
                return Response.error(errorMsg);
            }
            
            // 创建 Product 对象
            Product product = new Product();
            
            // 处理商品名称
            String productName = (String) data.get("productName");
            if (productName == null) {
                productName = (String) data.get("product_name");
            }
            product.setProductName(productName);
            
            // 处理基本字段
            product.setType((String) data.get("type"));
            product.setCategory((String) data.get("category"));
            product.setUnit((String) data.get("unit"));
            product.setDescription((String) data.get("description"));
            
            // 处理数值字段
            if (data.get("price") != null) {
                product.setPrice(new BigDecimal(data.get("price").toString()));
            }
            if (data.get("stock") != null) {
                product.setStock(Integer.valueOf(data.get("stock").toString()));
            }
            
            // 处理所有者信息
            Long ownerId = null;
            if (data.get("ownerId") != null) {
                ownerId = Long.valueOf(data.get("ownerId").toString());
            } else if (data.get("owner_id") != null) {
                ownerId = Long.valueOf(data.get("owner_id").toString());
            }
            product.setOwnerId(ownerId);
            
            String ownerType = (String) data.get("ownerType");
            if (ownerType == null) {
                ownerType = (String) data.get("owner_type");
            }
            product.setOwnerType(ownerType);
            
            // 处理状态
            String status = (String) data.get("status");
            product.setStatus(status != null ? status : "on_sale");
            
            // 处理收获日期
            String harvestDateStr = (String) data.get("harvestDate");
            if (harvestDateStr == null) {
                harvestDateStr = (String) data.get("harvest_date");
            }
            if (harvestDateStr != null && !harvestDateStr.trim().isEmpty()) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    product.setHarvestDate(sdf.parse(harvestDateStr));
                } catch (ParseException e) {
                    throw new RuntimeException("收获日期格式错误");
                }
            }
            
            // 处理图片路径，只保存文件名
            if (data.containsKey("image")) {
                String imagePath = (String) data.get("image");
                // 如果包含路径，只取文件名
                if (imagePath.contains("/")) {
                    imagePath = imagePath.substring(imagePath.lastIndexOf("/") + 1);
                }
                product.setImageUrl(imagePath);
                logger.info("设置商品图片名称: {}", imagePath);
            }
            
            // 打印处理后的对象
            logger.info("处理后的Product对象详细信息:");
            logger.info("- 商品名称: {}", product.getProductName());
            logger.info("- 类型: {}", product.getType());
            logger.info("- 分类: {}", product.getCategory());
            logger.info("- 价格: {}", product.getPrice());
            logger.info("- 单位: {}", product.getUnit());
            logger.info("- 库存: {}", product.getStock());
            logger.info("- 状态: {}", product.getStatus());
            logger.info("- 所有者ID: {}", product.getOwnerId());
            logger.info("- 所有者类型: {}", product.getOwnerType());
            logger.info("- 图片名称: {}", product.getImageUrl());
            
            Product savedProduct = productService.createProduct(product);
            return Response.success("添加成功", savedProduct);
        } catch (Exception e) {
            logger.error("添加商品失败", e);
            return Response.error("添加商品失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Response<?> updateProduct(
            @PathVariable Long id,
            @RequestBody Product product
    ) {
        try {
            product.setProductId(id);
            Product updated = productService.updateProduct(id, product);
            return Response.success("更新成功", updated);
        } catch (Exception e) {
            logger.error("更新农产品失败", e);
            return Response.error("更新农产品失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Response<?> deleteProduct(@PathVariable Long id) {
        try {
            productService.deleteProduct(id);
            return Response.success("删除成功", null);
        } catch (Exception e) {
            logger.error("删除农产品失败", e);
            return Response.error("删除农产品失败: " + e.getMessage());
        }
    }

    @PatchMapping("/{id}/status")
    public Response<?> updateStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> body
    ) {
        try {
            String status = body.get("status");
            productService.updateStatus(id, status);
            return Response.success("状态更新成功", null);
        } catch (Exception e) {
            logger.error("更新农产品状态失败", e);
            return Response.error("更新农产品状态失败: " + e.getMessage());
        }
    }

    @PostMapping("/{id}/stock")
    public Response<?> updateStock(
            @PathVariable Long id,
            @RequestBody Map<String, Object> body
    ) {
        try {
            Integer amount = body.get("amount") != null ? 
                Integer.valueOf(body.get("amount").toString()) : null;
            
            if (amount == null) {
                return Response.error("库存变更数量不能为空");
            }

            boolean success = productService.updateStock(id, amount);
            
            if (success) {
                return Response.success("库存更新成功", null);
            } else {
                return Response.error("库存更新失败：库存不足或产品不存在");
            }
        } catch (NumberFormatException e) {
            logger.error("库存数量格式错误", e);
            return Response.error("库存数量格式错误");
        } catch (Exception e) {
            logger.error("更新库存失败", e);
            return Response.error("更新库存失败: " + e.getMessage());
        }
    }
} 